package org.uim.cricket.storage.queries;

import java.util.Set;

import org.uim.cricket.entities.FullSeries;
import org.uim.cricket.entities.match.CricketMatch;

public class SeriesQueryGenerator extends QueryGenerator {

	private FullSeries series = null;
	private String seriesType = null;
	
	public SeriesQueryGenerator(CricketMatch theMatch, FullSeries series, String type) {
		super(theMatch);
		this.series = series;
		this.seriesType = type;
	}

	@Override
	public String generateQuery() throws Exception {
		StringBuilder query = new StringBuilder("CALL sp_Insert_Series(");
		query.append(this.series.getId()).append(",");
		this.appendQuery(query, encodeSQL(this.series.getFullname()), 256, false);
		this.appendQuery(query, this.series.getSeason(), 8, false);
		query.append(this.series.isDrawn()).append(",");
		this.appendQuery(query, encodeSQL(this.series.getTeamWon()), 128, true);
		this.appendQuery(query, this.series.getMargin(), 8, true);
		query.append(this.series.getTotalMatches()).append(",");
		this.appendQuery(query, seriesType, 32, false);
		this.appendQuery(query, this.getMatch().getId().getPrefix(), 8, false, false);
		query.append(");\n");
		
		if (this.series.getParticipatedCountries()!=null && this.series.getParticipatedCountries().size() > 0) {
			query.append(this.insertParticipatedTeams(this.series.getParticipatedCountries())).append("\n");
		}
		
		return query.toString();
	}
	
	private String insertParticipatedTeams(Set<String> participatedTeams) throws Exception {
		StringBuilder allq = new StringBuilder();
		for (String team : participatedTeams) {
			StringBuilder query = new StringBuilder("CALL sp_Insert_Series_ParticipatedTeam(");
			query.append(this.series.getId()).append(",");
			this.appendQuery(query, encodeSQL(team), 128, false, false);
			query.append(");");
			
			allq.append(query.toString()).append("\n");
		}
		return allq.toString();
	}
	
	public void setSeries(FullSeries series) {
		this.series = series;
	}
	
	public FullSeries getSeries() {
		return series;
	}
	
	public void setSeriesType(String seriesType) {
		this.seriesType = seriesType;
	}
	
	public String getSeriesType() {
		return seriesType;
	}

}
